//
//  MenuLabel.swift
//  MutaChat
//
//  Created by Kevin on 2018/3/23.
//  Copyright © 2018年 kevin. All rights reserved.
//

import UIKit

class MenuLabel: UILabel {
    var deleteSegue: ClickSegue?
    
    var menuVC = UIMenuController.shared

    var isOpenLongGesture: Bool = true {
        didSet {
            self.addLongPressGesture()
        }
    }
    
    override var canBecomeFirstResponder: Bool {
        return true
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        if isOpenLongGesture {
            self.addLongPressGesture()
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        if isOpenLongGesture {
            self.addLongPressGesture()
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        if action == #selector(copyText(_:)) || action == #selector(deleteText(_:)) {
            return true
        }else{
            return false
        }
    }
    
    override func copy(_ sender: Any?) {
        let pastBoard = UIPasteboard.general
        pastBoard.string = self.text
    }
    
    @objc func copyText(_ sender: Any?){
        let pastBoard = UIPasteboard.general
        pastBoard.string = self.text
    }
    
    @objc func deleteText(_ sender: Any?) {
        self.deleteSegue!()
    }
}

extension MenuLabel {
    func addLongPressGesture() {
        self.isUserInteractionEnabled = true
        let longPressGesture = UILongPressGestureRecognizer.init(target: self, action: #selector(longPressAction(gesture:)))
        self.addGestureRecognizer(longPressGesture)
    }

    @objc func longPressAction(gesture: UILongPressGestureRecognizer){
        NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: "长按手势"), object: nil)
        if gesture.state == .began {            
            self.becomeFirstResponder()
            let copyItem = UIMenuItem(title: "复制", action: #selector(copyText(_:)))
            let deleteItem = UIMenuItem(title: "删除", action: #selector(deleteText(_:)))
            menuVC.menuItems = [copyItem, deleteItem]
            if menuVC.isMenuVisible {
                return
            }
            menuVC.setTargetRect(bounds, in: self)
            menuVC.setMenuVisible(true, animated: true)
        }
        if gesture.state == .ended {

        }
    }
}
